package com.jarvis.view;

import java.util.Iterator;
import java.util.List;

import com.jarvis.adapter.ConfigListViewAdapter;
import com.jarvis.db.ConfigOpenHelper;
import com.jarvis.model.ConfigModel;
import com.jarvis.view.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class MyFirstAppActivity extends Activity {
	/** Called when the activity is first created. */
	
	private ConfigOpenHelper configOpenHelper = new ConfigOpenHelper(this);
	
	private  List<ConfigModel> listItem;
	
	private ConfigListViewAdapter listItemAdapter;
	
	private AlertDialog addConfigDialog;
	
	private AlertDialog confirmDeleteConfigDialog;
	
	private Menu menu;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		 //绑定Layout里面的ListView  
        ListView list = (ListView) findViewById(R.id.config_list);  
        //生成动态数组，加入数据  
        listItem = configOpenHelper.searchAllConfig();
        //生成适配器的Item和动态数组对应的元素  
       listItemAdapter = new ConfigListViewAdapter(this,listItem,//数据源   
            R.layout.configlistitem);  
       
        //添加并且显示  
        list.setAdapter(listItemAdapter); 
        
        //添加点击事件
        list.setOnItemClickListener(new ListItemClickListener());
          
          
	}
	
	

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		super.onPrepareOptionsMenu(menu);
		menu.clear();
		this.menu = menu;
		if(listItemAdapter.isShowCheckbox()){
			
			getMenuInflater().inflate(R.menu.main_menu_delete, menu);
		}else{
			getMenuInflater().inflate(R.menu.main_menu, menu);
		}
		
		return true;
	}


	public void showAddConfigActivity(MenuItem item) {

		if(item.getItemId() == R.id.add_config){
			createAddConfigDialog(MyFirstAppActivity.this).show();
		}
		
	}
	
	
	
	public AlertDialog createAddConfigDialog(final Context context){
		if(addConfigDialog == null){
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setIcon(R.drawable.ic_add);
			builder.setTitle(R.string.title_config_add);
			LayoutInflater inflater = LayoutInflater.from(context);
			builder.setView(inflater.inflate(R.layout.addconfig, null));
			builder.setPositiveButton(R.string.value_save, new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int buttonid) {
					// TODO Auto-generated method stub
					AlertDialog d = (AlertDialog)dialog;
					EditText numberField = (EditText) d.findViewById(R.id.target_num);
					EditText contentField = (EditText) d.findViewById(R.id.post_content);
					EditText countField = (EditText) d.findViewById(R.id.post_count);
					
					if(numberField.getText().toString().trim().equals("")){
						d.setTitle(R.string.tip_targetnum);
						d.show();
						return;
					}
					if(contentField.getText().toString().trim().equals("")){
						d.setTitle(R.string.tip_content);
						d.show();
						return;
					}
					if(countField.getText().toString().trim().equals("")){
						d.setTitle(R.string.tip_count);
						d.show();
						return;
					}
					
					ConfigModel configModel = new ConfigModel(numberField.getText().toString(), contentField.getText().toString(), Integer.parseInt(countField.getText().toString()));
					configModel.setLast_edit(System.currentTimeMillis());
					
					try {
						configOpenHelper.saveConfig(configModel);
						Toast.makeText(context, R.string.info_save_config_success, Toast.LENGTH_LONG).show();
						reloadConfigs();
						listItemAdapter.notifyDataSetChanged();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						Log.w("config", e);
						Toast.makeText(context, R.string.info_save_config_failure, Toast.LENGTH_LONG).show();
					}
					dialog.dismiss();
				}
			});
			
			builder.setNegativeButton(R.string.value_cancel, new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int arg1) {
					// TODO Auto-generated method stub
					AlertDialog d = (AlertDialog)dialog;
					EditText numberField = (EditText) d.findViewById(R.id.target_num);
					EditText contentField = (EditText) d.findViewById(R.id.post_content);
					EditText countField = (EditText) d.findViewById(R.id.post_count);
					numberField.setText("");
					contentField.setText("");
					countField.setText("");
					dialog.dismiss();
				}
			});
			
			addConfigDialog = builder.create();
		}
		addConfigDialog.setTitle(R.string.title_config_add);
		return addConfigDialog;
	}
	
	public AlertDialog createConfirmDeleteConfigDialog(final Context context){
		if(confirmDeleteConfigDialog == null){
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setIcon(R.drawable.ic_delete);
			builder.setTitle(R.string.title_config_remove);
			builder.setPositiveButton(R.string.value_delete, new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int buttonid) {
					// TODO Auto-generated method stub
					int success=0;
					Iterator<Integer> iterator = listItemAdapter.getSelectedItems().iterator();
					while(iterator.hasNext()){
						ConfigModel model = listItemAdapter.getValues().get(iterator.next());
						try {
							configOpenHelper.deleteConfig(model);
							success++;
						} catch (Exception e) {
							// TODO Auto-generated catch block
							Log.w("config", e);
						}
					}
					Toast.makeText(context, getText(R.string.info_delete_config_success_suffix).toString()+success+getText(R.string.info_delete_config_success_suffix).toString(), Toast.LENGTH_LONG).show();
					reloadConfigs();
					listItemAdapter.setShowCheckbox(!listItemAdapter.isShowCheckbox());
					listItemAdapter.getSelectedItems().clear();
					listItemAdapter.notifyDataSetChanged();
					if(menu != null){
						onPrepareOptionsMenu(menu);
					}
					dialog.dismiss();
				}
			});
			
			builder.setNegativeButton(R.string.value_cancel, new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int arg1) {
					// TODO Auto-generated method stub
					listItemAdapter.setShowCheckbox(false);
					listItemAdapter.getSelectedItems().clear();
					listItemAdapter.notifyDataSetChanged();
					if(menu != null){
						onPrepareOptionsMenu(menu);
					}
					dialog.dismiss();
				}
			});
			
			confirmDeleteConfigDialog = builder.create();
		}
		return confirmDeleteConfigDialog;
	}
	

	public void onRefreshClick(MenuItem item){
		if(listItem != null && listItemAdapter != null){
			reloadConfigs();
			listItemAdapter.notifyDataSetChanged();
			
		}
		
	}
	
	public void onSelectAllItemClick(MenuItem item){
		if(listItem != null && listItemAdapter != null){
			for(int i=0;i<listItem.size();i++){
				listItemAdapter.getSelectedItems().add(i);
			}
			listItemAdapter.notifyDataSetChanged();
		}
	}
	
	public void onDeleteClick(MenuItem item){

		if(listItemAdapter.isShowCheckbox() && listItemAdapter.getSelectedItems().size() > 0){
			createConfirmDeleteConfigDialog(this).show();
			return;
		}
		listItemAdapter.setShowCheckbox(!listItemAdapter.isShowCheckbox());
		listItemAdapter.notifyDataSetChanged();
		if(menu != null){
			onPrepareOptionsMenu(menu);
		}
	}
	
	private class ListItemClickListener implements OnItemClickListener{

		public void onItemClick(AdapterView<?> adapterView, View view, int position,
				long rowid) {
			if(!listItemAdapter.isShowCheckbox()){
				return;
			}
			if(listItemAdapter.getSelectedItems().contains(position)){
				listItemAdapter.getSelectedItems().remove(position);
			}else{
				listItemAdapter.getSelectedItems().add(position);
			}
			listItemAdapter.notifyDataSetChanged();
		}
		
	}


	public void reloadConfigs(){
		listItem.clear();
		listItem.addAll(configOpenHelper.searchAllConfig());
	}
	
	public void onCancelDeleteConfig(MenuItem item){
		listItemAdapter.setShowCheckbox(false);
		listItemAdapter.getSelectedItems().clear();
		listItemAdapter.notifyDataSetChanged();
		if(menu != null){
			onPrepareOptionsMenu(menu);
		}
	}
}